//
//  HMDataBase.m
//  HMMeituanHD
//
//  Created by apple on 2017/5/22.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMDataBase.h"

static FMDatabase *_db;

@implementation HMDataBase

/**
 * SQL语句:
 
 增: INSERT INTO 表名(字段1, 字段2) VALUES(值1, 值2)
 删: DELETE FROM 表名 WHERE 字段1 = 值
 改: UPDATE 表名 SET 字段n = 值 WHERE 字段1 = 值
 查: SELECT 字段名(*) FROM 表名 WHERE 字段1 = 值
 
 */


+(void)initialize{
    
    //设置数据库文件路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"collect.sqlite"];
    //创建数据库对象
    _db = [FMDatabase databaseWithPath:path];
    //打开数据库 建立连接
    if (![_db open]) {
        
        HMLog(@"数据库打开失败: %@", _db.lastError);
        return;
    }
    //创建表(不存在) 一定添加 IF NOT EXISTS
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_collect (id integer NOT NULL, deal_modal blob, deal_id text, PRIMARY KEY(id));"];
}

//保存收藏到本地数据库
+ (void)insertDealWithDealModel:(HMDealModel *)dealModel{

    //将模型保存为二进制数据,并且保留对象关系 使用归档 实现NSCoding协议(可以使用yymodal简化处理)
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dealModel];
    //插入数据
    [_db executeUpdateWithFormat:@"INSERT INTO t_collect(deal_modal,deal_id) VALUES(%@,%@)", data, dealModel.deal_id];
}

//删除收藏
+ (void)deleteDealWithDealModel:(HMDealModel *)dealModel{

    //删除数据
    [_db executeUpdateWithFormat:@"DELETE FROM t_collect WHERE deal_id = %@", dealModel.deal_id];
}


+ (BOOL)hasDeal:(HMDealModel *)dealModel{
    //获取满足条件的结果的数量: COUNT(*)
    //起别名:  AS 别名
    //执行查询
    FMResultSet *set = [_db executeQueryWithFormat:@"SELECT COUNT(*) AS collect_count FROM t_collect WHERE deal_id = %@", dealModel.deal_id];

    if ([set next]) { //取出下一条,默认没有取出数据
    
        int count = [set intForColumn:@"collect_count"];
        return count ? YES : NO;
    }
    return NO;
}

//一个方法如何实现多个返回值,利用指针传递地址
+ (NSArray<HMDealModel *> *)queryCollectsWithPage:(NSInteger)page error:(NSError **)error{

    //数据分页 LIMIT location,length
    /**
     *    
      location   length   page
         0          20      1
         20         20      2
         40         20      3
     
     location = (page - 1) * length
     
     */
    NSInteger length = 3;
    NSInteger location = (page - 1) * length;
    //可以根据主键进行倒序排列:  ORDER BY id(正序)  ORDER BY id DESC(降序)
    //执行查询
    FMResultSet *set = [_db executeQueryWithFormat:@"SELECT * FROM t_collect ORDER BY id DESC LIMIT %ld,%ld", location, length];
    NSMutableArray *temp = [NSMutableArray array];
    while ([set next]) {
        
        NSData *data = [set dataForColumn:@"deal_modal"];
        //二进制数据转为模型 解档
        HMDealModel *dealModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        //添加到数组中
        [temp addObject:dealModel];

    }
    
    if ([_db hadError]) {
        
        HMLog(@"查询失败:%@", _db.lastError);
        //使用指针运算符操作地址中的内容
        *error = _db.lastError;
    }
    
    return temp.copy;
}

@end
